package com.wzy.service.impl;

import com.alibaba.excel.ExcelReader;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.entity.SysUser;
import com.wzy.entity.dto.User.User;
import com.wzy.listener.ExcelListener;
import com.wzy.mapper.SysUserMapper;
import com.wzy.service.ExcelService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author wzy
 * @Date: 2022/1/25 10:16
 * @Description:
 */
@Service
public class ExcelServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ExcelService {
    private static final Logger logger = LoggerFactory.getLogger(ExcelServiceImpl.class);


    @Autowired
    private SysUserMapper sysUserMapper;
    /**
     * 导出用户信息
     * @param response
     * @throws IOException
     */
    @Override
    public void excelExport(HttpServletResponse response) throws IOException {
        //准备导出的数据
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("dept_id",102);
        List<SysUser> list = sysUserMapper.selectByMap(stringObjectHashMap);
        List<User> userList = list.stream().map(sysUser -> {
            User user = new User();
            BeanUtils.copyProperties(sysUser, user);
            return user;
        }).collect(Collectors.toList());
        logger.info("记录导出数据行数：{}",list.size());
        String fileName = "用户名单";
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xlsx");
        ServletOutputStream out = response.getOutputStream();
        //xls 一个 Sheet 最多支持 65535 行，如果数据要在一个 Sheet 中可以通过指定 ExcelFormat.Xlsx 来导出
        ExcelWriter writer = new ExcelWriter(out, ExcelTypeEnum.XLSX, true);
        Sheet sheet = new Sheet(1, 0, User.class);
        //设置自适应宽度
        sheet.setAutoWidth(Boolean.TRUE);
        sheet.setSheetName("用户名单");
        writer.write(userList,sheet);
        writer.finish();
        out.flush();
        response.getOutputStream().close();
        out.close();
    }

    /**
     * 导入用户信息
     * @param file
     * @throws IOException
     */
    @Override
    public void excelImport(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        //实例化实现了AnalysisEventListener接口的类
        ExcelListener listener = new ExcelListener();
        //传入参数
        ExcelReader excelReader = new ExcelReader(inputStream, ExcelTypeEnum.XLSX, null, listener);
        //读取信息
        excelReader.read(new Sheet(1, 1, User.class));
        //获取数据
        List<Object> list = listener.getDatas();
        List<SysUser> originalList = new ArrayList<SysUser>();
        logger.info("记录导入数据行数：{}", originalList.size());
        //转换数据类型
        for (int i = 0; i < list.size(); i++) {
            SysUser catagory = new SysUser();
            User user = (User) list.get(i);
            BeanUtils.copyProperties(user, catagory);
            originalList.add(catagory);
        }
        //对list进行去重并拿到新的list
        List<SysUser> lists = originalList.stream()
                .filter(s -> StringUtils.isNotBlank(s.getPhoneNumber()))
                .collect(Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<SysUser>(Comparator.comparing(SysUser::getLoginName))), ArrayList::new));
        //执行批量插入
        if (lists.size() > 0){
            logger.info("执行批量入库");
            this.saveBatch(lists);
            return;
        }

        logger.info("解析数据为空");
    }

}
